package com.awardsystem.Controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.awardsystem.Service.AchievementService;
import com.awardsystem.Service.ExportDataService;
import com.awardsystem.Service.SCIService;
import com.awardsystem.Service.UserService;
import com.awardsystem.Utils.ColumnTitleMap;
import com.awardsystem.entity.Achievement;
import com.awardsystem.entity.Project;
import com.awardsystem.entity.SCI;
import com.awardsystem.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
public class SCIController {
    @Autowired
    SCIService sciService;
    @Autowired
    ExportDataService exportDataService;
    @Autowired
    AchievementService achievementService;
    @Autowired
    UserService userService;
    @GetMapping("/getAllSci")
    public JSONObject getAll(){
        JSONObject ret=new JSONObject();
        List<Map<String,Object>> retList=new ArrayList<>();
        List<SCI> sciList=sciService.findAll();
//        for(SCI sci:sciList){
//            Map<String,Object> info=new HashMap<>();
//            info.put("id",sci.getId());
//            info.put("name",sci.getName());
//            info.put("createTime",sci.getCreateTime());
//            info.put("updateTime",sci.getUpdateTime());
//            info.put("url",sci.getUrl());
//            info.put("number",sci.getNumber());
//            info.put("filePath",sci.getFilePath());
//            info.put("funds",sci.getFunds());
//            info.put("correspoundUser",sci.getCorrespondUser());
//            retList.add(info);
//        }
//        ret.put("scis",retList);
        ret.put("scis",sciList);
        ret.put("success",true);
        ret.put("exc","success");
        return ret;
    }

    @GetMapping("/findSci")
    public JSONObject findSci(@RequestParam("name")String title){
        JSONObject ret=new JSONObject();
        List<SCI> sciList=sciService.findAll();
        List<SCI> retList=new ArrayList<>();
        for(SCI sci:sciList){
            if(sci.getName().equals(title)){
                retList.add(sci);
            }
        }
        ret.put("success",true);
        ret.put("exc","success");
        ret.put("scis",retList);
        return ret;
    }

    @PostMapping("/editSCI")
    public JSONObject editSCI(@RequestBody JSONObject params){
        JSONObject ret=new JSONObject();
        int id=Integer.parseInt(params.getString("id"));
        SCI sci=sciService.findById(id);
        if(sci==null){
            ret.put("success",false);
            ret.put("exc","不存在");
            return ret;
        }
        sci.setName(params.getString("name"));
        String firstAuthor=params.getString("firstAuthor");
        String corAuthor=params.getString("corAuthor");
        User firstAu=userService.findUserByPersonName(firstAuthor);
        if(firstAu==null){
            ret.put("success",false);
            ret.put("exc","不存在");
            return ret;
        }
        List<User> userList=sci.getAuthor();
        userList.set(0,firstAu);
        sci.setAuthor(userList);
        User corAu=userService.findUserByPersonName(corAuthor);
        if(corAu==null){
            ret.put("success",false);
            ret.put("exc","不存在");
            return ret;
        }
        sci.setCorrespondUser(corAu);
        JSONArray projects=params.getJSONArray("projects");
        List<Project> projectList=projects.toJavaList(Project.class);
        sci.setProjectList(projectList);
        LocalDate acceptDate = LocalDate.parse(params.getString("createTime"), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        LocalDate publicDate = LocalDate.parse(params.getString("updateTime"), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        sci.setCreateTime(acceptDate);
        sci.setUpdateTime(publicDate);
        sciService.save(sci);
        ret.put("success",true);
        ret.put("exc","success");
        return ret;
    }

    @PostMapping("/deleteSCI")
    public JSONObject deleteSCI(@RequestBody JSONObject params){
        JSONObject ret=new JSONObject();
        int id=Integer.parseInt(params.getString("id"));
        SCI sci=sciService.findById(id);
        if(sci==null){
            ret.put("success",false);
            ret.put("exc","不存在");
        }
        else{
            sciService.delete(sci);
            ret.put("success",true);
            ret.put("exc","success");
        }
        return ret;
    }

    @PostMapping("/excel")
    public void sciExcel(HttpServletResponse response,@RequestBody JSONObject params) throws IOException {
        List<Map<String ,Object>> sciList=new ArrayList<>();
        List<SCI> scis=new ArrayList<>();
        List<Integer> idList=params.getObject("idList",List.class);
        for(Integer id:idList){
            SCI sci=sciService.findById(id);
            scis.add(sci);
        }
        for(SCI sci:scis){
            HashMap<String,Object> info=new HashMap<>();
            info.put("sci_id",sci.getId());
            info.put("create_time",sci.getCreateTime());
            info.put("update_time",sci.getUpdateTime());
            info.put("name",sci.getName());
            info.put("url",sci.getUrl());
            info.put("correspond_user",sci.getCorrespondUser().getPersonName());
            info.put("first_author",sci.getAuthor().get(0).getPersonName());
            List<Achievement> achievements=sci.getAchievementList();
            int num=1;
            StringBuilder achievementInfo= new StringBuilder();
            for(Achievement achievement:achievements){
                String achievementName=Integer.toString(num);
                achievementName+=".";
                achievementName+=achievement.getName();
                achievementInfo.append(achievementName);
                achievementInfo.append(';');
                num++;
            }
            info.put("achievements", achievementInfo.toString());
            List<Project> projects=sci.getProjectList();
            num=1;
            StringBuilder projectInfo=new StringBuilder();
            for(Project project:projects){
                String projectName=Integer.toString(num);
                projectName+=".";
                projectName+=project.getName();
                projectInfo.append(projectName);
                projectInfo.append(';');
                num++;
            }
            info.put("projects",projectInfo.toString());
            sciList.add(info);
        }
        ArrayList<String> titleKeyList= new ColumnTitleMap("sci").getTitleKeyList();
        Map<String, String> titleMap = new ColumnTitleMap("sci").getColumnTitleMap();
        exportDataService.exportDataToEx(response, titleKeyList, titleMap, sciList);

    }

    @GetMapping("/allAchievement")
    public JSONObject getAllAchievement(){
        JSONObject ret=new JSONObject();
        List<Achievement> achievements=achievementService.findAchievementAll();
        ret.put("success",true);
        ret.put("exc","success");
        ret.put("achieve",achievements);
        return ret;
    }

    @PostMapping("/addAchieveToSci")
    public JSONObject addAchieveToSci(@RequestBody JSONObject params){
        JSONObject ret=new JSONObject();
        int sciId=Integer.parseInt(params.get("sci_id").toString());
        SCI sci=sciService.findById(sciId);
        int achId=Integer.parseInt(params.get("ach_id").toString());
        Achievement achievement=achievementService.findAchievementById(achId);
        if(sci==null||achievement==null){
            ret.put("success",false);
            ret.put("exc","不存在");
            return ret;
        }
        else{
            List<Achievement> achievements=sci.getAchievementList();
            if(!achievements.contains(achievement))achievements.add(achievement);
            sci.setAchievementList(achievements);
            sciService.save(sci);
            ret.put("success",true);
            ret.put("exc","success");
        }
        return ret;
    }
}
